package de.fh.ka.as.car.routing;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Point;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import de.fh.ka.as.car.routing.map.MapObject;
import de.fh.ka.as.car.routing.map.MapProvider;
import de.fh.ka.as.car.routing.map.RoutingPointMapObject;

public class MapDrawerCanvas extends View implements OnTouchListener {
	private Paint paint = new Paint();
	private MapProvider mapProvider;

	/**
	 * @param mapProvider
	 *           the mapProvider to set
	 */
	public void setMapProvider(MapProvider mapProvider) {
		this.mapProvider = mapProvider;
		this.postInvalidate();
	}

	public MapDrawerCanvas(Context context) {
		super(context);
		setFocusable(true);
		setFocusableInTouchMode(true);

		this.setOnTouchListener(this);

		paint.setColor(Color.WHITE);
		paint.setAntiAlias(true);
		paint.setStyle(Style.FILL_AND_STROKE);

	}

	public MapDrawerCanvas(Context context, MapProvider mapProvider) {
		super(context);
		this.setFocusable(true);
		this.setFocusableInTouchMode(true);
		this.mapProvider = mapProvider;
		this.setOnTouchListener(this);

		paint.setColor(Color.WHITE);
		paint.setAntiAlias(true);
		paint.setStyle(Style.FILL_AND_STROKE);

	}

	@Override
	public void onDraw(Canvas canvas) {
		paint.setColor(Color.WHITE);
		for (int i = 0; i < getHeight(); i += 20) {
			canvas.drawLine(0, i, getWidth(), i, paint);
		}

		for (int i = 0; i < getWidth(); i += 20) {
			canvas.drawLine(i, 0, i, getHeight(), paint);
		}

		if (mapProvider != null) {
			for (MapObject mo : mapProvider.getMap().values()) {
				mo.draw(canvas, paint);
			}
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if (mapProvider != null) {
			if (event.getAction() == MotionEvent.ACTION_UP) {
				int x = (int) event.getX();
				int y = (int) event.getY();

				int rasterX = x - (x % 20);
				int rasterY = y - (y % 20);

				MapObject mo = new RoutingPointMapObject(new Point(rasterX, rasterY));
				if (!this.mapProvider.getMap().containsKey(mo.getPoint())) {
					this.mapProvider.getMap().put(mo.getPoint(), mo);
					invalidate();
				}
			}
		}
		return true;
	}
}
